package vip.xiaonuo.biz.modular.detect.service.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import vip.xiaonuo.biz.modular.detect.BizDetectStatusEnum;
import vip.xiaonuo.dev.modular.file.entity.DevFile;
import vip.xiaonuo.dev.modular.file.mapper.DevFileMapper;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

/**
 * @author
 * @date 2023/11/1、19:07
 */
@Component
@Slf4j
public class DetectImageUtil {

    private static final String TRUE = "True";
    private static final String FALSE = "False";

    private final PythonProcessorAsync pythonProcessorAsync;
    private final PythonProcessor pythonProcessor;

    @Resource
    private DevFileMapper devFileMapper;

    private final ExecutorService taskExecutor;

    @Autowired
    public DetectImageUtil(PythonProcessorAsync pythonProcessorAsync, PythonProcessor pythonProcessor, ExecutorService taskExecutor){
        this.pythonProcessorAsync = pythonProcessorAsync;
        this.pythonProcessor = pythonProcessor;
        this.taskExecutor = taskExecutor;
    }

    /**
     * 获取图像路径
     *
     * @param imgId 图片 ID
     * @return {@link String}
     */
    public String getImagePath(String imgId){
        DevFile image = devFileMapper.selectById(imgId);
        return image.getStoragePath();
    }

    public String executeProcess(String imagePath){
        log.info("待检测图片的路径：{}",imagePath);
        try {
            pythonProcessor.startPythonProcess();
            String res = pythonProcessor.processImage(imagePath);
            log.info("检测结果：{}",res);
            return judgeResult(res);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public boolean closeProcess(){
        try {
            pythonProcessor.closePythonProcess();
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public Future<String> executeProcessAsync(final String imagePath) {
        log.info("待检测图片的路径：{}", imagePath);
        Callable<String> task = () -> {
            try {
                String res = pythonProcessorAsync.processImage(imagePath);
                log.info("检测结果：{}", res);
                return judgeResult(res);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        };
        return taskExecutor.submit(task); // 提交任务到线程池
    }

    /**
     * 判断结果
     *
     * @param res
     * @return {@link String}
     */
    public String judgeResult(String res){
        if (TRUE.equals(res)) {
            return BizDetectStatusEnum.SICK.getValue();
        } else if(FALSE.equals(res)) {
            return BizDetectStatusEnum.HEALTHY.getValue();
        }
        else{
            return "error";
        }
    }
}
